import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerApi } from '@/api/customer'
import type { CustomerContact } from '@/types/customer'
import { formatDateTime } from '@/utils/format'
import type { ApiResponse } from '@/types/api'

// 查询表单
const queryForm = reactive({
  page: 1,
  limit: 10,
  keywords: '',
  customer_id: '',
})

// 联系人列表
const contactList = ref<CustomerContact[]>([])
const total = ref<number>(0)
const loading = ref<boolean>(false)

// 选中的联系人
const selectedContacts = ref<CustomerContact[]>([])

// 详情抽屉
const detailDrawerVisible = ref<boolean>(false)
const currentContact = ref<CustomerContact>({} as CustomerContact)

// 联系人操作抽屉
const contactDrawerVisible = ref<boolean>(false)
const contactOperationMode = ref<'add' | 'edit'>('add')
const currentContactId = ref<number | string>('')
const currentCustomerId = ref<number>(0)
const currentContactData = ref<CustomerContact | null>(null)

// 表单引用
const queryFormRef = ref<any>(null)

// 处理查询
const handleSearch = async () => {
  loading.value = true
  try {
    const params: any = {
      page: queryForm.page,
      limit: queryForm.limit,
    }

    if (queryForm.keywords) {
      params.keywords = queryForm.keywords
    }

    if (queryForm.customer_id) {
      params.customer_id = queryForm.customer_id
    }

    // 使用已定义的API方法获取联系人列表
    const response = await customerApi.getContactList(params)
    if (response && response.code === 0) {
      // 确保返回的是数组
      if (response.data?.list && Array.isArray(response.data.list)) {
        contactList.value = response.data.list
      } else {
        contactList.value = []
      }
      total.value = response.data?.total || 0
    } else {
      contactList.value = []
      total.value = 0
      ElMessage.error(response?.msg || '获取联系人列表失败')
    }
  } catch (error) {
    contactList.value = []
    total.value = 0
    console.error('获取联系人列表失败:', error)
    ElMessage.error('获取联系人列表失败')
  } finally {
    loading.value = false
  }
}

// 新增联系人
const handleAdd = () => {
  contactOperationMode.value = 'add'
  currentContactId.value = ''
  currentCustomerId.value = parseInt(queryForm.customer_id) || 0
  contactDrawerVisible.value = true
}

// 重置查询
const handleReset = () => {
  queryForm.keywords = ''
  queryForm.customer_id = ''
  queryForm.page = 1
  handleSearch()
}

// 查看联系人
const handleView = (row: CustomerContact) => {
  currentContact.value = row
  detailDrawerVisible.value = true
}

// 编辑联系人
const handleEdit = (row: CustomerContact) => {
  contactOperationMode.value = 'edit'
  currentContactId.value = row.id
  currentCustomerId.value = row.cid
  currentContactData.value = row
  contactDrawerVisible.value = true
}

// 删除联系人
const handleDelete = (row: CustomerContact) => {
  ElMessageBox.confirm(`确定要删除联系人"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await customerApi.deleteContact(row.id)
        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          handleSearch()
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除联系人失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 批量删除联系人
const handleBatchDelete = () => {
  if (selectedContacts.value.length === 0) {
    ElMessage.warning('请先选择要删除的联系人')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的${selectedContacts.value.length}个联系人吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const deletePromises = selectedContacts.value.map(item =>
          customerApi.deleteContact(item.id)
        )
        const results = await Promise.all(deletePromises)

        // 检查所有删除操作是否都成功
        const allSuccess = results.every(result => result && result.code === 0)

        if (allSuccess) {
          ElMessage.success('批量删除成功')
          handleSearch()
        } else {
          ElMessage.error('部分删除失败')
          handleSearch()
        }
      } catch (error) {
        console.error('批量删除联系人失败:', error)
        ElMessage.error('批量删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 设为默认联系人
const handleSetDefault = (row: CustomerContact) => {
  ElMessageBox.confirm(`确定要将"${row.name}"设为默认联系人吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(async () => {
      try {
        const response = await customerApi.setDefaultContact({ id: row.id, cid: row.cid })
        if (response && response.code === 0) {
          ElMessage.success('设置成功')
          handleSearch()
        } else {
          ElMessage.error(response?.msg || '设置失败')
        }
      } catch (error) {
        console.error('设置默认联系人失败:', error)
        ElMessage.error('设置失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}

// 处理选择变化
const handleSelectionChange = (selection: CustomerContact[]) => {
  selectedContacts.value = selection
}

// 处理联系人操作成功
const handleContactSuccess = () => {
  handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryForm.limit = val
  queryForm.page = 1
  handleSearch()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  queryForm.page = val
  handleSearch()
}

// 关闭详情抽屉
const closeDetailDrawer = () => {
  detailDrawerVisible.value = false
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  queryForm,
  contactList,
  total,
  loading,
  selectedContacts,
  detailDrawerVisible,
  contactDrawerVisible,
  currentContact,
  currentCustomerId,
  currentContactId,
  currentContactData,
  contactOperationMode,
  queryFormRef,

  // 方法
  handleSearch,
  handleReset,
  handleAdd,
  handleView,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  handleSetDefault,
  handleSelectionChange,
  handleSizeChange,
  handleCurrentChange,
  closeDetailDrawer,
  handleContactSuccess,
  formatDateTime,
}
